package com.example.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.crm.entity.Customer;
import com.example.crm.entity.CustomerTagRelation;
import com.example.crm.mapper.CustomerMapper;
import com.example.crm.mapper.CustomerTagRelationMapper;
import com.example.crm.service.CustomerCategoryService;
import com.example.crm.service.CustomerService;
import com.example.crm.service.CustomerTagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 客户服务实现类
 */
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements CustomerService {

    @Autowired
    private CustomerTagService customerTagService;
    
    @Autowired
    private CustomerCategoryService customerCategoryService;
    
    @Autowired
    private CustomerTagRelationMapper customerTagRelationMapper;

    @Override
    public IPage<Customer> listCustomersByPage(Map<String, Object> params) {
        int current = params.get("current") != null ? Integer.parseInt(params.get("current").toString()) : 1;
        int size = params.get("size") != null ? Integer.parseInt(params.get("size").toString()) : 10;
        
        Page<Customer> page = new Page<>(current, size);
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        
        // 构建查询条件
        if (params.get("name") != null && !StringUtils.isEmpty(params.get("name").toString())) {
            queryWrapper.like("name", params.get("name").toString());
        }
        
        if (params.get("phone") != null && !StringUtils.isEmpty(params.get("phone").toString())) {
            queryWrapper.like("phone", params.get("phone").toString());
        }
        
        if (params.get("categoryId") != null) {
            queryWrapper.eq("category_id", params.get("categoryId"));
        }
        
        queryWrapper.eq("deleted", 0);
        queryWrapper.orderByDesc("create_time");
        
        IPage<Customer> result = this.page(page, queryWrapper);
        
        // 填充每个客户的分类名称
        result.getRecords().forEach(customer -> {
            if (customer.getCategoryId() != null) {
                customer.setCategoryName(customerCategoryService.getById(customer.getCategoryId()).getName());
            }
        });
        
        return result;
    }

    @Override
    public Customer getCustomerDetail(Long id) {
        Customer customer = this.getById(id);
        if (customer != null) {
            // 设置分类名称
            if (customer.getCategoryId() != null) {
                customer.setCategoryName(customerCategoryService.getById(customer.getCategoryId()).getName());
            }
            
            // 获取客户标签
            LambdaQueryWrapper<CustomerTagRelation> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CustomerTagRelation::getCustomerId, id);
            List<CustomerTagRelation> relations = customerTagRelationMapper.selectList(wrapper);
            
            List<Long> tagIds = relations.stream()
                    .map(CustomerTagRelation::getTagId)
                    .collect(Collectors.toList());
            
            customer.setTagIds(tagIds);
            customer.setTags(customerTagService.listByIds(tagIds));
        }
        return customer;
    }

    @Override
    @Transactional
    public boolean addCustomer(Customer customer, List<Long> tagIds) {
        customer.setCreateTime(LocalDateTime.now());
        customer.setUpdateTime(LocalDateTime.now());
        customer.setDeleted(0);
        
        // 处理年营业额为null的情况
        if (customer.getAnnualRevenue() == null) {
            customer.setAnnualRevenue(new BigDecimal("0.00"));
        }
        
        boolean result = this.save(customer);
        
        // 保存标签关系
        if (result && tagIds != null && !tagIds.isEmpty()) {
            saveCustomerTags(customer.getId(), tagIds);
        }
        
        return result;
    }

    @Override
    @Transactional
    public boolean updateCustomer(Customer customer, List<Long> tagIds) {
        customer.setUpdateTime(LocalDateTime.now());
        
        // 处理年营业额为null的情况
        if (customer.getAnnualRevenue() == null) {
            customer.setAnnualRevenue(new BigDecimal("0.00"));
        }
        
        boolean result = this.updateById(customer);
        
        // 更新标签关系
        if (result && tagIds != null) {
            // 先删除旧关系
            LambdaQueryWrapper<CustomerTagRelation> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CustomerTagRelation::getCustomerId, customer.getId());
            customerTagRelationMapper.delete(wrapper);
            
            // 保存新关系
            if (!tagIds.isEmpty()) {
                saveCustomerTags(customer.getId(), tagIds);
            }
        }
        
        return result;
    }

    @Override
    public Map<String, Object> getCustomerStatistics() {
        Map<String, Object> statistics = new HashMap<>();
        
        // 总客户数
        long totalCount = this.count(new LambdaQueryWrapper<Customer>().eq(Customer::getDeleted, 0));
        statistics.put("totalCount", totalCount);
        
        // 按分类统计客户数
        List<Map<String, Object>> categoryStatsList = this.baseMapper.countGroupByCategory();
        // 将List<Map>转换为前端期望的格式
        Map<String, Object> categoryStats = new HashMap<>();
        for (Map<String, Object> item : categoryStatsList) {
            Object categoryId = item.get("category_id");
            Object count = item.get("count");
            if (categoryId != null) {
                categoryStats.put(categoryId.toString(), count);
            }
        }
        statistics.put("categoryStats", categoryStats);
        
        // 近30天新增客户数
        LocalDateTime thirtyDaysAgo = LocalDateTime.now().minusDays(30);
        long newCustomerCount = this.count(
                new LambdaQueryWrapper<Customer>()
                        .eq(Customer::getDeleted, 0)
                        .ge(Customer::getCreateTime, thirtyDaysAgo)
        );
        statistics.put("newCustomerCount", newCustomerCount);
        
        return statistics;
    }
    
    /**
     * 保存客户标签关系
     */
    private void saveCustomerTags(Long customerId, List<Long> tagIds) {
        List<CustomerTagRelation> relations = tagIds.stream().map(tagId -> {
            CustomerTagRelation relation = new CustomerTagRelation();
            relation.setCustomerId(customerId);
            relation.setTagId(tagId);
            relation.setCreateTime(LocalDateTime.now());
            relation.setUpdateTime(LocalDateTime.now());
            relation.setIsDeleted(0);
            return relation;
        }).collect(Collectors.toList());
        
        relations.forEach(customerTagRelationMapper::insert);
    }
} 